﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;

namespace Domain.Infrastructure.ServiceExtensions
{
    public static class SwaggerSetup
    {
        public static IServiceCollection AddClientSwaggerSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            var apiName = "接口文档";
            var apiVersion = "v1";

            services.AddSwaggerGen((s) =>
            {
                s.SwaggerDoc(apiVersion, new OpenApiInfo
                {
                    Version = apiVersion,
                    Title = apiName,
                    Description = apiName + apiVersion,
                    Contact = new OpenApiContact { Name = apiName, Email = "CESE@CHIVOX.COM", Url = new Uri("https://www.chivox.com/") },
                });
                s.OrderActionsBy(o => o.RelativePath);

                try
                {
                    //生成API XML文档
                    var basePath = AppContext.BaseDirectory;
                    var xmlPath = Path.Combine(basePath, "doc.xml");
                    s.IncludeXmlComments(xmlPath);
                }
                catch (Exception ex)
                {
                    
                }

                // 开启加权小锁
                s.OperationFilter<AddResponseHeadersFilter>();
                s.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                // 在header中添加token，传递到后台
                s.OperationFilter<SecurityRequirementsOperationFilter>();

                // 必须是 oauth2
                s.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）\"",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey
                });

            });
            return services;
        }
    }
}
